#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import string
import webapp2

template = string.Template("""<!DOCTYPE>
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title></title>
    <script type="text/javascript">
    var log = $JSON;
    </script>
    <script type="text/javascript" src="//www.google.com/jsapi"></script>
    <script type="text/javascript" src="logic.js"></script>
  </head>
  <body>
    <div id="dashboard">
        <div id="chart" style='width: 915px; height: 300px;'></div>
        <div id="control" style='width: 915px; height: 50px;'></div>
    </div>
  </body>
</html>""")

class MainHandler(webapp2.RequestHandler):
    def post(self):
        self.response.headers['Content-Type'] = 'text/html'

        file_data = self.request.POST.get('logfile')
        file_contents = file_data.file.read()
        try:
          parsed_file_contents = json.dumps(json.loads(file_contents))
        except:
          self.response.out.write('Could not parse uploaded file, was it in the right format? (a JSON-dumped list of objects with start and end fields)')
          return
        self.response.out.write(template.substitute({'JSON': parsed_file_contents}))

app = webapp2.WSGIApplication([('/upload', MainHandler)],
                              debug=True)
